import { Component, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { CallService } from '../call.service';

@Component({
  selector: 'app-files',
  templateUrl: './files.page.html',
  styleUrls: ['./files.page.scss'],
})
export class FilesPage implements OnInit {
  files = [];
  private start = '';

  constructor(
    private callService: CallService,
    private alertCtrl: AlertController,
  ) { }

  async ngOnInit() {
    this.files = await this.callService.call('getFiles', {
      def: [
        { id: 1, isDir: true, name: '/aa', formatTime: '2021-10-01 11:00:33', formatSize: 4096 },
        { id: 2, isDir: false, name: '/aa', formatTime: '2021-10-01 11:00:33', formatSize: 4096, wordCount: 222 },
      ]
    }, '');

    if (this.files.length > 0) {
      this.start = this.files[this.files.length - 1].name;
    }
  }

  async delFile(name: string) {
    console.log('xx');
    const alert = await this.alertCtrl.create({
      header: '是否删除索引？',
      message: `是否删除索引文件: ${name}`,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
        }, {
          text: '确定',
          handler: async () => {
            await this.callService.call('delFile', { msg: '删除中...' }, name);
            await this.ngOnInit();
          }
        }
      ]
    });
    await alert.present();
  }

  // 加载数据
  async loadData(event: any) {
    const fs = await this.callService.call('getFiles', {}, this.start);

    fs.shift();

    if (fs.length > 0) {
      this.start = fs[fs.length - 1].name;
    }

    this.files.push(...fs);
    event.target.complete();

    if (fs.length === 0) {
      event.target.disabled = true;
    }
  }
}
